package com.bwie.service;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.domain.User;
import com.bwie.mapper.UserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: lrz
 * @Date: 2024/11/5 09:08
 * @Description:
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public R login(LoginInfoVo loginInfoVo) {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone",loginInfoVo.getUserName());

        User user = userMapper.selectOne(userQueryWrapper);
        if(user==null){
            return R.ERROR(500,"手机号不存在");
        }
        if(!loginInfoVo.getUserPass().equals(user.getPassword())){
            return R.ERROR(500,"密码不正确");
        }
        String key2 = "code-"+loginInfoVo.getUserName();
        String s = stringRedisTemplate.opsForValue().get(key2);
        if(!loginInfoVo.getUserCode().equals(s)){
            return R.ERROR(500,"验证码不正确");
        }
        String key = "token-"+user.getId();
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getId())
                .claim("userName", user.getUsername())
                .compact();
        stringRedisTemplate.opsForValue().set(key,token,30, TimeUnit.MINUTES);
        user.setToken(token);
        return R.OK(user);
    }

    @Override
    public R getCode(String phone) {
        String code = RandomUtil.randomNumbers(4);
        Boolean aBoolean = MobileMessageUtil.sendMobileMessage(phone, code);
        if(!aBoolean){
            MobileMessageUtil.sendMobileMessage(phone, code);
        }
        String key = "code-"+phone;
        stringRedisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);

        System.out.println("验证码为："+code);

        return R.OK();
    }
}
